<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form :form="form" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-item label="被调整人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-select-user-by-dep @change="changeUser" v-decorator="['userId', validatorRules.userId]"/>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="调整项目" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <!--
              <j-dict-select-tag type="list" v-decorator="['fieldId', validatorRules.fieldId]" :trigger-change="true" dictCode="salary_fields,field_name,id" placeholder="请选择调整项目"/>
         <a-select-option v-for="d in formOptions" :key="d.value">{{d.text}}</a-select-option>
         -->
              <a-select v-decorator="['fieldId', validatorRules.fieldId]" placeholder="请选择调整项目" @change="getOldSalary">
                <a-select-option v-for="d in formOptions" :key="d.value" >{{ d.text }}</a-select-option>
              </a-select>

            </a-form-item>
          </a-col>
          <a-col :span="24" v-if="isShow">
            <a-form-item label="调整前薪资" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input disabled v-decorator="['fieldDefaultOld', validatorRules.fieldDefaultOld]" placeholder="请输入调整前薪资"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="调整幅度" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['adjustValue', validatorRules.adjustValue]" placeholder="请输入调整幅度" @change="salaryCount"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="调整方式" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag
                type="radio"
                v-decorator="['adjustType', validatorRules.adjustType]"
                :trigger-change="true"
                @change="salaryCount"
                dictCode="adjust_type"
                placeholder="请选择调整方式"/>
            </a-form-item>
          </a-col>

          <a-col :span="24" v-if="isShow">
            <a-form-item label="调整后薪资" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input disabled v-decorator="['fieldDefaultNew', validatorRules.fieldDefaultNew]" placeholder="请输入调整后薪资"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="调整原因" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-textarea v-decorator="['adjustReason', validatorRules.adjustReason]" rows="4" placeholder="请输入调整原因"/>
            </a-form-item>
          </a-col>
          <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
            <a-button @click="submitForm">提 交</a-button>
          </a-col>
        </a-row>
      </a-form>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import { validateDuplicateValue } from '@/utils/util'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import JSelectUserByDep from '@/components/jeecgbiz/JSelectUserByDep'
  import JDictSelectTag from '@/components/dict/JDictSelectTag'
  import { dicCode } from '@/api/salaryAdjust'

  export default {
    name: 'SalaryAdjustForm',
    components: {
      JFormContainer,
      JSelectUserByDep,
      JDictSelectTag
    },
    props: {
      // 流程表单data
      formData: {
        type: Object,
        default: () => {},
        required: false
      },
      // 表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      // 表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        formOptions: [],
        isShow: true,
        form: this.$form.createForm(this),
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        confirmLoading: false,
        validatorRules: {
          userId: {
            rules: [
              { required: true, message: '请输入被调整人ID!' }
            ]
          },
          fieldId: {
            rules: [
              { required: true, message: '请输入调整项目ID!' }
            ]
          },
          adjustValue: {
            initialValue: 0,
            rules: [
              { required: true, message: '请输入调整幅度!' }
            ],
            getValueFromEvent: (event) => {
                return event.target.value.replace(/[^\d]/g, '')
            }
          },
          adjustType: {
            initialValue: '1',
            rules: [
              { required: true, message: '请输入调整方式,1上调，2下调!' }
            ]
          },
          fieldDefaultOld: {
            initialValue: 0,
            rules: [
              { required: true, message: '请输入调整前薪资!' }
            ]
          },
          fieldDefaultNew: {
            initialValue: 0,
            rules: [
              { required: true, message: '请输入调整hou薪资!' }
            ]
          }

        },
        url: {
          add: '/salary/salaryAdjust/add',
          edit: '/salary/salaryAdjust/edit',
          queryById: '/salary/salaryAdjust/queryById'
        }
      }
    },
    computed: {

      formDisabled() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return true
          }
        }
        return false
      }
    },
    created () {
      // 如果是流程中表单，则需要加载流程表单data
      this.showFlowData()
      this.getCode()
    },
    methods: {

      getCode() {
        dicCode().then((res) => {
          if (res.success) {
            this.formOptions = res.result
          }
        })
      },

      changeUser(value) {
        if (value) {
          const len = value.split(',').length
          if (len <= 1) {
            this.isShow = true
            this.getOldSalary()
          } else {
            this.isShow = false
          }
        }
      },
      getOldSalary() {
        // console.log('come', this.form.getFieldValue('userId'), this.form.getFieldValue('fieldId'))
        this.$nextTick(() => {
            getAction('/salary/salaryAdjust/queryByFieldId', { userId: this.form.getFieldValue('userId'), fieldId: this.form.getFieldValue('fieldId') }).then((res) => {
                console.log('resresres', res)
                if (res.code === 200) {
                   this.form.setFieldsValue({ fieldDefaultOld: res.message })
                   this.salaryCount()
                } else {
                  this.form.setFieldsValue({ fieldDefaultOld: 0 })
                  this.salaryCount()
                }
            })
        })
      },
      salaryCount() {
        this.$nextTick(() => {
          const oldVal = this.form.getFieldValue('fieldDefaultOld')
          const changeVal = this.form.getFieldValue('adjustValue') || 0
          const type = this.form.getFieldValue('adjustType')
          let newVal = 0
          if (type === '1') {
            newVal = Number(oldVal) + Number(changeVal)
          } else if (type === '2') {
            newVal = Number(oldVal) - Number(changeVal)
          } else {
            newVal = 0
          }
          this.form.setFieldsValue({ fieldDefaultNew: newVal })
        })
      },
      add () {
        this.edit({})
        this.isShow = true
      },
      edit (record) {
        this.form.resetFields()
        this.isShow = true
        this.model = Object.assign({}, record)
        this.visible = true
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'userId', 'fieldId', 'adjustValue', 'adjustType', 'fieldDefaultOld', 'fieldDefaultNew', 'adjustReason'))
        })
      },
      // 渲染流程表单数据
      showFlowData() {
        if (this.formBpm === true) {
          let params = { id: this.formData.dataId }
          getAction(this.url.queryById, params).then((res) => {
            if (res.success) {
              this.edit(res.result)
            }
          })
        }
      },
      submitForm () {
        const that = this
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true
            let httpurl = ''
            let method = ''
            if (!this.model.id) {
              httpurl += this.url.add
              method = 'post'
            } else {
              httpurl += this.url.edit
              method = 'put'
            }
            let formData = Object.assign(this.model, values)
            console.log('表单提交数据', formData)
            httpAction(httpurl, formData, method).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            }).finally(() => {
              that.confirmLoading = false
            })
          }
        })
      },
      popupCallback(row) {
        this.form.setFieldsValue(pick(row, 'userId', 'fieldId', 'adjustValue', 'adjustType', 'fieldDefaultOld', 'fieldDefaultNew', 'adjustReason'))
      }
    }
  }
</script>
